<?php
/**
 * 意见反馈
 *
 * User: kaikaic
 * Date: 2018/10/26
 * Time: 0:09
 */

namespace app\psy\controller;

use app\psy\service\AccountService;
use app\psy\service\FeedbackService;
use controller\BasicAdmin;
use service\ConfigService;
use think\Db;

class Feedback extends BasicAdmin {

    protected $table = "Feedback";

    public function index() {
        $this->title = "意见反馈";
        $query = array();
        $query['name'] = $this->request->get("name");
        $query['status'] = intval($this->request->get("status"));

        $db = Db::name($this->table);
        if ($query['name']) {
            $db->whereLike("name", "%{$query['name']}%");
        }

        return parent::listRecord($db);
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);

        $cfgStatus = ConfigService::cfgFeedbackStatus();
        for ($i=0; $i<$size; $i++) {
            $data[$i]['account'] = "";
            $account = AccountService::getInstance()->find($data[$i]['account_id']);
            if ($account) {
                $data[$i]['account'] = $account['nick_name'];
            }

            $data[$i]['status_txt'] = "";
            if (isset($cfgStatus[$data[$i]['status']])) {
                $data[$i]['status_txt'] = $cfgStatus[$data[$i]['status']];
            }
        }

        $this->assign('cfg_status', $cfgStatus);
    }

    /**
     * 意见反馈-回复
     */
    public function reply() {
        if ($this->request->isGet()) {
            $id = $this->request->get('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $feedback = FeedbackService::getInstance()->find($id);
            if (empty($feedback)) {
                $this->error('记录不存在，请重新操作!');
            }

            $account = AccountService::getInstance()->find($feedback['account_id']);
            if ($account) {
                $feedback['account'] = $account['real_name'];
            }else {
                $feedback['account'] = "匿名用户";
            }

            return view('form', [
                'title'=>'回复意见反馈',
                'vo'=>$feedback,
            ]);
        }

        if ($this->request->isPost()) {
            $id = $this->request->post('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $data = $this->request->post();
            if ($this->doInsertAction($data)) {
                $this->success('回复成功！', '');
            }else {
                $this->error('回复失败，请稍候再试！');
            }
        }
    }

    /**
     * 数据写入
     */
    protected function doInsertAction($data) {
        $id = intval($data['id']);
        $data['status'] = 2;

        return FeedbackService::getInstance()->update($data, $id);
    }
}

